<?php

class DiaryController extends SecuredController
{
	public function actionIndex()
	{
		$this->render('index');
	}
	
	public function actionToday()
	{
		if (Yii::app()->request->isAjaxRequest)
		{
	        Yii::app()->clientScript->scriptMap['*.js'] = false;
	        
		    $sendJS = true;
		    
		    if (isset($_GET['Diary_page'])) $sendJS = false;
		    
		    $dataProvider = new CActiveDataProvider('Diary', array(
		    	'criteria' => array(
		    		'order' => 'rec_date DESC',
		        	'with' => array('Text'),
		        	'together' => true,
		        ),
		    ));
		    
		    $this->renderPartial('_tabToday', array('dataProvider' => $dataProvider), false, $sendJS);
	    
		    Yii::app()->end();
		}
	}
	
	public function actionNewRecord()
	{
	    if (Yii::app()->request->isAjaxRequest)
	    {
	        $text = new Texts();
	        $diary = new Diary();
	        $text->user_id = Yii::app()->user->id;
	        $diary->user_id = Yii::app()->user->id;
	        
	        if (isset($_POST['Diary']) && isset($_POST['Texts']))
	        {
	            // Data sent via POST. Process.
	            // $this->performAjaxValidation($diary, $text);
	            
	            $text->attributes = $_POST['Texts'];
	            $diary->attributes = $_POST['Diary'];
	            
	            $result = false;
	            $errorMsg = '';
	            
	            if ($text->save())
	            {
	                $diary->txt_id = $text->txt_id;
	                
	                if ($diary->save())
	                {
	                    $result = true;
	                } 
	                else
	                {
	                    $errorMsg = $this->convertArrayToText($diary->getErrors());
	                }
	            }
	            else
	            {
	                $errorMsg = $this->convertArrayToText($text->getErrors());
	            }
	            
	            if ($result)
	            {
	                //$this->redirect($this->createUrl('/diary/today', array('ajax' => 'diaryRecs')));
	                $this->run('today');
	            }
	            else
	            {
	                echo $errorMsg;
	            }
	            
	            Yii::app()->end();
	        }
	        else
	        {
	            // No data sent. Show form.
	            
	            Yii::app()->clientScript->scriptMap['*.js'] = false;
	            
	            $sendJS = true;
	            
	            if (isset($_GET['Diary_page'])) $sendJS = false;
	            
	            $this->renderPartial('newRecord', array('diary' => $diary, 'text' => $text), false, true);
	            
	            Yii::app()->end();
	        }
	    }
	}

	// -----------------------------------------------------------
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($diary, $text)
	{
		if(isset($_POST['ajax']) && $_POST['ajax'] === 'new-rec-form')
		{
			echo CActiveForm::validate($diary);
			echo CActiveForm::validate($text);
			Yii::app()->end();
		}
	}
	
	private function convertArrayToText($arr)
	{
	    $resultLine = '';
	    
	    foreach ($arr as $key => $value)
	    {
	        $resultLine .= $key.' -> ';
	        foreach ($value as $rep) { $resultLine .= $rep; }
	        $resultLine .= '<br />';
	    }
	    
	    return $resultLine;
	} 
}